package cn.imatu.framework.flyway;

import cn.imatu.framework.flyway.entity.ResourceScript;
import cn.imatu.framework.flyway.executor.FlywayExecutor;
import cn.imatu.framework.flyway.executor.FlywayExecutorFactory;
import cn.imatu.framework.flyway.properties.LyFlywayProperties;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;

/**
 * @author shenguangyang
 */
@Slf4j
@AutoConfiguration
@ComponentScan(basePackages = "cn.imatu.framework.flyway")
@MapperScan(basePackages = "cn.imatu.framework.flyway.mapper")
@EnableConfigurationProperties(LyFlywayProperties.class)
public class LyFlywayAutoConfiguration implements InitializingBean {
    @Resource
    private DataSource dataSource;
    @Resource(name = "lyFlywayProperties")
    private LyFlywayProperties flywayProperties;
    @Resource
    private FlywayManager flywayManager;
    @Resource
    private FlywayExecutorFactory flywayExecutorFactory;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (!Boolean.TRUE.equals(flywayProperties.getEnabled())) {
            log.info("===> 未使能 flyway");
            return;
        }
        String databaseProductName = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
        log.info("===> flyway 加载 [{}]", databaseProductName);
        FlywayExecutor flywayExecutor = flywayExecutorFactory.getInstance(databaseProductName);
        flywayExecutor.initTable();

        List<ResourceScript> scriptList = flywayManager.loadResource();
        for (ResourceScript resourceScript : scriptList) {
            flywayManager.initConfig(flywayExecutor, resourceScript);
        }
    }
}
